﻿using Forum.BaseController;
using Forum.Infrastructure;
using Forum.Service.Interface;

namespace Forum.Controllers
{
    /// <summary>
    /// 文章信息
    /// </summary>
    [Route("Api/BlogPost")]
    public class BlogPostController : BaseController<IPostService>
    {
        private readonly ICategoryService _categoryService;
        private readonly IBlogService _blogService;
        private readonly ICommentService _commentService;

        public BlogPostController(IPostService defaultService,
                                  ILogger<BaseController<IPostService>> logger,
                                  ICategoryService categoryService,
                                  IBlogService blogService,
                                  ICommentService commentService) : base(defaultService, logger)
        {
            _categoryService = categoryService;
            _blogService = blogService;
            _commentService = commentService;
        }

        /// <summary>
        /// 批量查询文章
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        //[AllowAnonymous]
        [HttpGet]
        public ApiResponsePaged<Post> GetList([FromQuery] PostQueryParameters param)
        {
            var pagedList = DefaultService.GetPagedList(param);
            return new ApiResponsePaged<Post>
            {
                msg = "Get posts list",
                data = pagedList.ToList(),
                total = pagedList.Total,
                haveMore = pagedList.Total > param.Page * param.PageSize
            };
        }

        /// <summary>
        /// 根据ID查询文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ApiResponse<Post> Get(string id)
        {
            var post = DefaultService.GetById(id);
            return post == null ? ApiResponse.NotFound() : new ApiResponse<Post>(post);
        }

        /// <summary>
        /// 查询博客的浏览量
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/ViewsCount")]
        public int GetViewsCount(string id)
        {
            return DefaultService.GetViewsCount(id);
        }

        /// <summary>
        /// 删除博客
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public ApiResponse Delete(string id)
        {
            var post = DefaultService.GetById(id);
            if (post == null) return ApiResponse.NotFound($"博客不存在");
            DefaultService.Delete(id);
            return ApiResponse.OK();
        }

        /// <summary>
        /// 新增博客
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResponse<Post> Add(PostReq req)
        {
            var post = req.MapTo<PostReq, Post>();
            var category = _categoryService.GetById(post.CategoryId);
            if (category == null)
                return ApiResponse.Error($"分类 {post.CategoryId} 不存在！");

            post.Id = Guid.NewGuid().ToString();
            post.CreationTime = DateTime.Now;
            post.LastUpdateTime = DateTime.Now;

            var categories = new List<Category> { category };
            var parent = category.Parent;
            while (parent != null)
            {
                categories.Add(parent);
                parent = parent.Parent;
            }

            categories.Reverse();
            //post.Categories = string.Join(",", categories.Select(a => a.Id));

            return new ApiResponse<Post>(DefaultService.Insert(post));
        }

        /// <summary>
        /// 更新博客
        /// </summary>
        /// <param name="id"></param>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public ApiResponse<Post> Update(string id, PostUpdateReq req)
        {
            var post = DefaultService.GetById(id);
            if (post == null) return ApiResponse.NotFound("博客不存在");

            // mapper.Map(source) 得到一个全新的对象
            // mapper.Map(source, dest) 在 source 对象的基础上修改
            post = req.MapTo<PostUpdateReq, Post>();
            post.LastUpdateTime = DateTime.Now;
            return new ApiResponse<Post>(DefaultService.Update(post));
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public ApiResponse UploadImage(IFormFile file)
        {
            //var post = DefaultService.GetById(id);
            //if (post == null) return ApiResponse.NotFound("博客不存在");
            var imgUrl = DefaultService.UploadImage(file);
            return ApiResponse.OK("", new
            {
                imgUrl,
                imgName = Path.GetFileNameWithoutExtension(imgUrl)
            });
        }

        /// <summary>
        /// 获取文章里的图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/[action]")]
        public ApiResponse<List<string>> Images(string id)
        {
            var post = DefaultService.GetById(id);
            if (post == null) return ApiResponse.NotFound("博客不存在");
            return new ApiResponse<List<string>>(DefaultService.GetImages(post));
        }

        /// <summary>
        /// 设置为推荐博客
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id}/[action]")]
        public ApiResponse<FeaturedPost> SetFeatured(string id)
        {
            var post = DefaultService.GetById(id);
            return post == null
                ? ApiResponse.NotFound()
                : new ApiResponse<FeaturedPost>(_blogService.AddFeaturedPost(post));
        }

        /// <summary>
        /// 取消推荐博客
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id}/[action]")]
        public ApiResponse CancelFeatured(string id)
        {
            var post = DefaultService.GetById(id);
            if (post == null) return ApiResponse.NotFound("博客不存在");
            var rows = _blogService.DeleteFeaturedPost(post);
            return ApiResponse.OK($"delete {rows} rows.");
        }

        /// <summary>
        /// 设置置顶（只能有一篇置顶）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id}/[action]")]
        public ApiResponse<TopPost> SetTop(string id)
        {
            var post = DefaultService.GetById(id);
            if (post == null) return ApiResponse.NotFound("博客不存在");
            var (data, rows) = _blogService.SetTopPost(post);
            return new ApiResponse<TopPost> { data = data, msg = $"删除了{rows}篇旧的置顶文章." };
        }

        /// <summary>
        /// 取消置顶
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id}/[action]")]
        public ApiResponse CancelTop(string id)
        {
            var post = DefaultService.GetById(id);
            if (post == null) return ApiResponse.NotFound("博客不存在");
            var rows = _blogService.DeleteTopPost(post);
            return ApiResponse.OK();
        }

        /// <summary>
        /// 查询博客的评价
        /// </summary>
        /// <param name="postId"></param>
        /// <returns></returns>
        [HttpPost("{postId}/GetComment")]
        public ApiResponse<List<Comment>> GetCommentByPostId(string postId)
        {
            var list = _commentService.GetCommentById(postId);
            return list == null ? ApiResponse.NotFound() : new ApiResponse<List<Comment>>(list);
        }
    }
}
